const connection = require('../db/mysql')

class CdkService {
    // 生成兑换码
    async generate(code, status, userId) {
        let statement = 'INSERT INTO cdkey(code, status, userId) VALUES(?, ?, ?);'
        let [ result ] = await connection.execute(statement, [code, status, userId])
        return result
    }

    // 根据code和userId获取兑换码
    async getCdkByCodeAndUserId(code, userId) {
        let statement = 'SELECT * FROM cdkey WHERE code = ? AND userId = ?;'
        let [ result ] = await connection.execute(statement, [code, userId])
        return result
    }

    // 兑换奖品(兑换余额)
    async exchange(code, userId) {
        let statement = 'UPDATE cdkey SET status = 1, updateAt = NOW() WHERE code = ? AND userId = ?;'
        let [ result ] = await connection.execute(statement, [code, userId])
        return result
    }

    // 根据id删除兑换码
    async remove(cdkId) {
        let statement = 'DELETE FROM cdkey WHERE id = ?;'
        let [ result ] = await connection.execute(statement, [cdkId])
        return result
    }

    // 获取兑换码列表
    async list(userId) {
        let statement = 'SELECT * FROM cdkey WHERE userId = ?;'
        let [ result ] = await connection.execute(statement, [userId])
        return result
    }
}

module.exports = new CdkService()